<template>
    <div v-if="op">

        <h1>我的资源</h1>
        <SearchTypeSelector v-model="FType" />
        <input type="text" v-model="FName" placeholder="文件名" />
        <button @click="allResources(FName, FType, -1)">搜索</button>
        <TraverseResource :resourceList="resourceList1" @select="handleSelect"></TraverseResource>

    </div>

    <div v-if="!op">
        <button @click="returnList">返回</button><br>
        <button @click="toLookInformation">查看</button>
        <button @click="toUpdateInformation">修改基本信息</button>
        <button @click="toUpdateImages">更换图片</button>
        <button @click="deleteResource">删除</button>

        <div v-if="lookInformation">
            <h1>具体信息</h1>
            <button @click="returnList">返回</button>
            <div v-if="resourceInformation">
                <div v-if="resourceInformation">
                    <p><strong>ID:</strong> {{ resourceInformation.id }}</p>
                    <p><strong>资源名称:</strong> {{ resourceInformation.resourceName }}</p>
                    <p><strong>资源类型:</strong> {{ resourceInformation.resourceType }}</p>
                    <p><strong>版本:</strong> {{ resourceInformation.version }}</p>
                    <p><strong>自定义名称:</strong> {{ resourceInformation.customerName }}</p>
                    <p><strong>更新时间:</strong> {{ resourceInformation.updateTime }}</p>
                    <p><strong>下载次数:</strong> {{ resourceInformation.downloadCount }}</p>
                    <p><strong>描述:</strong> {{ resourceInformation.description }}</p>
                    <p><strong>提供者:</strong> {{ resourceInformation.providerName }}</p>
                </div>
                <div v-else>
                    <DelayedDisplay>
                        <p>获取失败</p>
                    </DelayedDisplay>
                </div>
            </div>

            <div v-if="imageList.length > 0">
                <div v-for="(image, index) in imageList" :key="index" style="margin-bottom: 10px;">
                    <img :src="image" alt="资源图片" style="max-width: 100%; height: auto;" />
                </div>
            </div>
            <div v-else>
                <DelayedDisplay>
                    <p>未上传图片</p>
                </DelayedDisplay>
            </div>
        </div>



        <div v-if="updateInformation">
            <h1>修改基本信息</h1>
            <div v-if="resourceInformation">
                <div v-if="resourceInformation">
                    <p>
                        <strong>ID:</strong>
                        {{ resourceInformation.id }}
                    </p>
                    <p>
                        <strong>资源名称:</strong>
                        {{ resourceInformation.resourceName }}
                    </p>
                    <p><strong>资源类型:</strong>
                        <UploadTypeSelector v-model="resourceInformation.resourceType" />
                    </p>
                    <p>
                        <strong>版本:</strong>
                        <input type="text" v-model="resourceInformation.version" placeholder="版本号" />
                    </p>
                    <p>
                        <strong>自定义名称:</strong>
                        <input type="text" v-model="resourceInformation.customerName" placeholder="自定义命名（不对外展示）" />
                    </p>
                    <p>
                        <strong>更新时间:</strong>
                        {{ resourceInformation.updateTime }}
                    </p>
                    <p><strong>下载次数:</strong> {{ resourceInformation.downloadCount }}</p>
                    <p>
                        <strong>描述:</strong>
                        <input type="text" v-model="resourceInformation.description" placeholder="简介" />
                    </p>
                    <p>
                        <strong>提供者:</strong>
                        {{ resourceInformation.providerName }}
                    </p>
                </div>
                <div v-else>
                    <DelayedDisplay>
                        <p>获取失败</p>
                    </DelayedDisplay>
                </div>
            </div>
            <button @click="updateInf()">保存</button>
        </div>

        <div v-if="updateImages">
            <p>上传图片</p>
            <input type="file" multiple accept="image/*" @change="handleImages" />
            <div v-if="images.length > 0">
                <h2>预览图：</h2>
                <div v-for="(image, index) in imageUrls" :key="index">
                    <button @click="removeImage(index)">×</button>
                    <img :src="image" width="100" alt="Image Preview" />
                </div>
            </div>
            <button @click="uploadRImages(resourceId)">保存</button>
        </div>
    </div>


</template>

<style scoped></style>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { Resource } from '@/model/resource'
import SearchTypeSelector from '@/components/SearchTypeSelector.vue'
import TraverseResource from '@/components/TraverseResource.vue'
import { deleteResourceAPI, getResourceImagesAPI, getResourceInformationAPI, searchResourceAPI, updateRInformationAPI, uploadRImagesAPI } from '@/service/API'
import UploadTypeSelector from '@/components/UploadTypeSelector.vue'
import router from '@/router'
import store from '@/store'

//响应数据
const resourceList1 = ref<Resource[]>([])
const FType = ref<string>('all')
const FName = ref<string>('')
const formData = new FormData();

const op = ref(true)
let resourceId: number
const updateInformation = ref(false)
const updateImages = ref(false)
const lookInformation = ref(true)

const images = ref<File[]>([])
const imageUrls = ref<string[]>([])

/**
 * 搜索资源
 * 
 * @remarks
 * 该函数用于搜索资源，当前的搜索条件是文件名、资源类型和版本号
 * @param {string} name - 文件名
 * @param {string} version - 版本号
 * @param {number} providerId - 提供者ID，-1 表示所有提供者
 * @returns Promise<{ success: boolean, resources: Resource[] | null }>
 */
const allResources = async (name: string, version: string, providerId: number) => {
    const { R_searchResourceAPI, resources } = await searchResourceAPI(name, version, providerId)
    if (R_searchResourceAPI) {
        if (resources) {
            resourceList1.value = resources
        }
    }
}

/**
 * 选择资源时的回调函数
 * 
 * @param id - 选择的资源的 ID
 */
const handleSelect = (id: number) => {
    // 选择的资源的 ID
    resourceId = id
    console.log('点击了 id=' + resourceId + ' 的资源');
    // 获取资源信息和图片
    getResource()
    // 隐藏资源列表
    op.value = false
}

const imageList = ref<string[]>([])
const resourceInformation = ref<Resource | null>(null)
/**
 * 获取资源信息和图片
 * 
 * @remarks
 * 该函数用于获取资源的信息和图片，通过对应的 API
 * @returns Promise<void>
 */
const getResource = async () => {
    // 重置图片列表和资源信息
    imageList.value = []
    resourceInformation.value = null
    try {
        // 通过 GET 请求获取资源信息
        const { R_getResourceInformationAPI, resource } = await getResourceInformationAPI(resourceId)
        if (R_getResourceInformationAPI) {
            console.log('资源信息已加载');
            resourceInformation.value = resource
        } else {
            console.log('资源信息未加载' + R_getResourceInformationAPI);
        }
        // 通过 GET 请求获取资源图片
        const { R_getResourceImagesAPI, images } = await getResourceImagesAPI(resourceId)
        if (R_getResourceImagesAPI && images) {
            console.log('资源图片已加载' + R_getResourceImagesAPI);
            imageList.value = images
        } else {
            console.log('资源图片未加载' + R_getResourceImagesAPI);
        }
    } catch (error) {
        // 捕获并记录获取资源信息和图片的错误
        console.error('获取资源信息和图片失败:', error)
    }
}



/**
 * 返回资源列表
 * 
 * @remarks
 * 该函数用于返回资源列表，回到资源列表的界面
 */
const returnList = () => {
    // 使资源列表可见
    op.value = true
}
const toLookInformation = () => {
    lookInformation.value = true
    updateImages.value = false
    updateInformation.value = false
}
const toUpdateInformation = () => {
    lookInformation.value = false
    updateImages.value = false
    updateInformation.value = true
}
const toUpdateImages = () => {
    lookInformation.value = false
    updateImages.value = true
    updateInformation.value = false
}


const handleImages = (event: Event) => {
    const target = event.target as HTMLInputElement
    if (!target.files) return
    const selectedFiles = Array.from(target.files)
    images.value.push(...selectedFiles)
    target.value = ''
    selectedFiles.forEach(file => {
        const imageUrl = URL.createObjectURL(file)
        imageUrls.value.push(imageUrl) // 存储生成的 URL
    })
}
const removeImage = (index: number) => {
    images.value.splice(index, 1)
    imageUrls.value.splice(index, 1)
}
const uploadRImages = async (id: number) => {
    // 检查是否有图片文件
    if (!(images.value.length > 0)) {
        console.log("图片获取数量为零");
        alert('请选择图片')
        return
    }
    // 创建 FormData 对象并附加资源 ID 和图片文件
    const formDataImage = new FormData();
    formDataImage.append('resourceId', id.toString());
    for (let i = 0; i < images.value.length; i++) {
        formDataImage.append('images', images.value[i]);  // 注意：append 多个同名字段
    }
    const { R_uploadRImagesAPI } = await uploadRImagesAPI(id, formDataImage)
    if (R_uploadRImagesAPI) {
        alert('更改成功')
    } else {
        alert('更改失败')
    }
}

const updateInf = async () => {
    if (resourceInformation.value) {
        const { R_updateRInformationAPI } = await updateRInformationAPI(resourceInformation.value)
        if (R_updateRInformationAPI) {
            alert('更改成功')
        } else {
            alert('更改失败')
        }
    } else {
        alert('请检查信息完整性')
    }

}

const deleteResource = async () => {
    const choice = window.confirm('点击确定删除')
    if (choice) {
        console.log('开始删除id：' + resourceId);

        const { R_deleteResourceAPI } = await deleteResourceAPI(resourceId)
        if (R_deleteResourceAPI) {
            alert('删除成功')
            allResources(FName.value, FType.value, Number(store.state.id))
            returnList()
        } else {
            alert('删除失败')
        }
    }
}

//页面初始化加载
onMounted(() => {
    const token = localStorage.getItem('token');
    if (!token) {
        alert('上传功能需要登陆')
        router.push('/login')
        return
    }
      
    allResources(FName.value, FType.value, Number(store.state.id))
})

watch([FType, FName], () => {
    formData.set('resourceName', FName.value);
    formData.set('resourceType', FType.value);
})

</script>
